﻿// Copyright 2006 - Ricardo Stuven (rstuven@gmail.com)
//
// This file is part of MsSqlSpatial.
// MsSqlSpatial is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// MsSqlSpatial is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public License
// along with MsSqlSpatial; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using GeoAPI.Geometries;
using GisSharpBlog.NetTopologySuite.LinearReferencing;
using MsSqlSpatial;

public partial class UserDefinedFunctions
{
	/// <summary>
	/// PostGIS docs:
	/// 
	/// line_substring(linestring, start, end)
	/// 
	/// Return a linestring being a substring of the input one 
	/// starting and ending at the given fractions of total 2d length. 
	/// 
	/// Second and third arguments are float8 values between 0 and 1. 
	/// 
	/// If 'start' and 'end' have the same value this is equivalent to line_interpolate_point(). 
	///
	/// See line_locate_point() for computing the line location nearest to a Point. 
	/// 
	/// Note
	/// Since release 1.1.1 this function also interpolates M and Z values (when present), while prior releases set them to unspecified values. 
	/// 
	/// </summary>
	/// <param name="ewkb"></param>
	/// <returns></returns>
	[SqlFunction(IsDeterministic = true)]
	public static SqlBytes LineSubstring(SqlBytes ewkb, SqlDouble start, SqlDouble end)
	{
		IGeometry geometry = ConvertGeometry.ToGeometry(ewkb);
		if (geometry != null && !start.IsNull && !end.IsNull)
		{
			LengthIndexedLine indexedLine = new LengthIndexedLine(geometry);
			double length = geometry.Length;
			double startIndex = start.Value * length;
			double endIndex = end.Value * length;
			return ConvertGeometry.ToSqlBytes(indexedLine.ExtractLine(startIndex, endIndex), geometry.SRID);
		}
		return SqlBytes.Null;
	}
};

